<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <title>Marcotte in a Worker with Blocking Syscalls</title>

  <!-- Include xterm.js (CSS + JS) -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.1.0/css/xterm.css" />
  <script src="https://cdn.jsdelivr.net/npm/xterm@5.1.0/lib/xterm.js"></script>

  <style>
    html, body {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      overflow: hidden; /* No scrollbars */
    }
    #terminal {
      height: 100%;
      width: 100%;
    }
  </style>
</head>
<body>
  <!--<h1 style="display:none;">Marcotte + Worker + Blocking WebSocket + xterm.js</h1>-->

  <!-- The terminal goes full screen in #terminal -->
  <div id="terminal"></div>

  <!-- Optional button to start the WASM program -->
  <!--<button id="startBtn" style="display:none;">Start Wasm Program</button>-->
  <!--<pre id="log" style="display:none;"></pre> [> optional logging <]-->

  <script>
    // Set up xterm in the main thread
    const term = new Terminal({
      rows: 100,
      cols: 100, //
      convertEol: true,
      cursorBlink: true,
    });
    term.open(document.getElementById('terminal'));
    term.write("loading boxer env... \n");

    // Create the Worker
    const worker = new Worker('marcotte_worker.js');

    worker.onmessage = (evt) => {
      const { cmd, text, returnValue } = evt.data;

      switch (cmd) {
        case 'wasmReady':
          log("Wasm is ready! Starting main() in 2 seconds...");
          // Optionally auto-start the program
          setTimeout(() => {
            worker.postMessage({ cmd: 'callMain' });
          }, 2000);
          break;

        case 'callMainDone':
          log("Wasm program finished with returnValue=" + returnValue);
          break;

        case 'hostWriteStdout':
          // A line (or partial line) from stdout
          term.write(text);
          break;

        default:
          console.log("Worker message:", evt.data);
          break;
      }
    };

    // If you want a button to manually start the program, uncomment:
    /*
    document.getElementById('startBtn').style.display = 'inline';
    document.getElementById('startBtn').addEventListener('click', () => {
      worker.postMessage({ cmd: 'initWasm', payload: { wasmUrl: 'client.wasm' } });
      setTimeout(() => worker.postMessage({ cmd: 'callMain' }), 2000);
    });
    */

    // Immediately request the worker to load the wasm
    worker.postMessage({ cmd: 'initWasm', payload: { wasmUrl: 'client.wasm' } });

    function log(msg) {
      const logDiv = document.getElementById('log');
      logDiv.style.display = 'block';
      logDiv.textContent += msg + "\n";
    }
  </script>
</body>
</html>

